using Sage.Http.Authentication;

namespace Sage.Http.Core.Handlers
{
    /// <summary>
    /// 请求认证处理器，负责处理所有与认证相关的逻辑
    /// </summary>
    internal class RequestAuthHandler
    {
        private IAuthenticationProvider? _authProvider;

        /// <summary>
        /// 获取认证提供者
        /// </summary>
        public IAuthenticationProvider? AuthProvider => _authProvider;

        /// <summary>
        /// 设置认证提供者
        /// </summary>
        /// <param name="authProvider">认证提供者</param>
        public void SetAuthentication(IAuthenticationProvider authProvider)
        {
            _authProvider = authProvider ?? throw new ArgumentNullException(nameof(authProvider));
        }

        /// <summary>
        /// 应用认证到请求
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        public void ApplyAuthentication(HttpRequestMessage request)
        {
            ArgumentNullException.ThrowIfNull(request);

            _authProvider?.AuthenticateRequest(request);
        }

        /// <summary>
        /// 异步应用认证到请求
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <returns>表示异步操作的任务</returns>
        public async Task ApplyAuthenticationAsync(HttpRequestMessage request)
        {
            ArgumentNullException.ThrowIfNull(request);

            if (_authProvider != null)
            {
                await _authProvider.AuthenticateRequest(request);
            }
        }

        /// <summary>
        /// 清除认证设置
        /// </summary>
        public void Clear()
        {
            _authProvider = null;
        }

        /// <summary>
        /// 检查是否已设置认证
        /// </summary>
        /// <returns>如果已设置认证则返回true，否则返回false</returns>
        public bool HasAuthentication => _authProvider != null;
    }
}